using System.Collections.Generic;
using System.Linq;
using Toast.Core;
using Toast.Core.Interfaces;
using Toast.Extensions;

namespace Toast.ContentTypes
{
    public class LocalFileFormatter : InjectionFormatter
    {
        readonly string _packageKey;

        public LocalFileFormatter(string packageKey, string format)
            : base(format)
        {
            _packageKey = packageKey;
        }

        public override string Format(IContent javaScriptContent, bool seperate)
        {
            var typedScript = javaScriptContent as ICompressable;

            if (typedScript == null)
                return null;

            return seperate
                       ? InjectionFormatString.FormatWith(typedScript.ToEncodedUrl(ToastCore.HANDLER_URL_SEGMENT, _packageKey))
                       : typedScript.ToEncodedUrl("{0}", _packageKey);
        }

        public override string Format(IEnumerable<IContent> scripts, bool seperate)
        {
            if (scripts != null)
            {
                return seperate 
                    ? scripts.Select(x => Format(x, true)).Join("\r\n")
                    : InjectionFormatString.FormatWith(ToastCore.HANDLER_URL_SEGMENT.FormatWith(scripts.Select(x => Format(x, false)).Join("~"), _packageKey));
            }

            return null;
        }
    }
}